package cn.yj;

import com.rabbitmq.client.*;
import org.junit.Test;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author 永健
 * @since 2022-02-08 16:28
 */
public class MqServer {

    /**
     * 消费者
     * @throws IOException
     * @throws TimeoutException
     */
    @Test
    public void rec() throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("thisforyou.cn");
        factory.setPort(5672);
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        String queueName="TEST_QUEUE";
        // 队列名称，是否持久化，独占队列（仅限于此连接），是否自动删除队列
        channel.queueDeclare(queueName, true, false, false, null);

        channel.basicConsume(queueName,true, (consumerTag, message) -> System.out.println(new String(message.getBody())), consumerTag -> System.out.println("取消："+consumerTag));

        System.in.read();

    }


    /**
     * 生产者
     * @throws IOException
     * @throws TimeoutException
     */
    @Test
    public void push() throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("thisforyou.cn");
        factory.setPort(5672);
        Connection connection = factory.newConnection();
        factory.setVirtualHost("/");

        Channel channel = connection.createChannel();

        String queueName="TEST_QUEUE";
        channel.queueDeclare(queueName, false, false, false, null);
        String message = "Hello World!";
        channel.basicPublish("", queueName, null, message.getBytes());



    }
}
